package org.tcx.web.ajax;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorResources;
import org.tcx.common.DomUtil;
import org.tcx.common.LogUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class AjaxConfig {
	private static Log log = LogFactory.getLog(AjaxConfig.class);
	private final String configpath = "ajax.cfg.xml";
	private final String validatorpath = "ajax.validator.xml";
	private final String suffix = ".ajax";
	private Map<String, Action> actions;

	public Action getAction(String path) {
		path = path.substring(0, path.length() - suffix.length());
		return actions.get(path);
	}

	public void init() throws ParserConfigurationException, SAXException,
			IOException, ClassNotFoundException {
		log.debug("enter");
		InputStream config_in = getClass().getClassLoader().getResourceAsStream(
				configpath);
		log.debug(LogUtil.arg("config_in", config_in));
		InputStream validator_in = getClass().getClassLoader().getResourceAsStream(
				validatorpath);
		log.debug(LogUtil.arg("validator_in", validator_in));
		ValidatorResources resources = new ValidatorResources(validator_in);
		Document doc = DomUtil.parse(config_in);
		NodeList nodeList = doc.getElementsByTagName("action");
		actions = new HashMap<String, Action>();
		for (int i = 0; i < nodeList.getLength(); i++) {
			if (nodeList.item(i) instanceof Element) {
				Element actionEle = (Element) nodeList.item(i);
				String path = actionEle.getAttribute("path");
				log.debug(LogUtil.arg("path", path));
				String method = actionEle.getAttribute("method");
				log.debug(LogUtil.arg("method", method));
				String clazName = actionEle.getAttribute("class");
				log.debug(LogUtil.arg("clazName", clazName));
				Class<?> claz = Class.forName(clazName);
				Validator validator = new Validator(resources, path);
				Action action = new Action(path, method, claz, validator);
				actions.put(path, action);
			}
		}
	}
}
